import axios from 'axios'
import router from '@/router'
import URL from './baseUrl'
import { Toast } from 'vant'
import { Dialog } from 'vant'

const service = axios.create({
  baseURL: `${URL}`,
  timeout: 10000, // 请求超时时间
  withCredentials: true // 允许携带cookie
})
// 添加请求拦截器，在参数中加token
service.interceptors.request.use(
  config => {
    //浏览器参数
    config.headers['ZLINK-DEVICE'] = 'web'
    config.headers['ZLINK-VERSION'] = '0.0.0'
    // 将token添加到每一个接口的参数中
    // 判断请求的类型：如果是post请求就把默认参数拼到data里面；如果是get请求就拼到params里面
    const token = localStorage.getItem('ISTOKEN')
    if (localStorage.getItem('ISTOKEN')) {
      if (config.method === 'post') {
        config.data = {
          api_token: token,
          ...config.data
        }
      } else if (config.method === 'get') {
        config.params = {
          api_token: token,
          ...config.params
        }
      }
    } else {
      // 跳转到登录页面
      // router.push('/login')
    }
    return config
  },
  error => {
    return Promise.reject(error)
  })

// 添加请求拦截器
service.interceptors.response.use(
  response => {
    const res = response.data
    if (res.state != 0) {
     Toast(res.msg)
   }
    return response
  },
  async error => {
    Toast.clear()
    Dialog({
      message: '网络开小差啦~',
      closeOnClickOverlay: true
    })
    return Promise.reject(error)
  })

export default service
